<template>
  <div class="app-param">
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="参数名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入参数名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="参数键名" prop="configKey">
        <el-input v-model="queryParams.configKey" placeholder="请输入参数键名" clearable></el-input>
      </el-form-item>
      <el-form-item label="参数状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="启用" value="0"></el-option>
          <el-option label="禁用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :inline="true">
        <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
        <el-button icon="Refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div>
      <el-button type="primary" plain size="small" icon="Plus" @click="handleAdd">新增</el-button>
      <el-button type="danger" plain size="small" icon="Delete" @click="handleDelete">删除</el-button>
      <el-button type="warning" plain size="small" icon="Lock" @click="handlePassword">密码修改</el-button>
    </div>

    <el-table
      :data="configList"
      v-loading="loading"
      stripe
      ref="multipleTableRef"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="编号" width="55" align="center" />
      <el-table-column prop="name" label="名称" align="center" />
      <el-table-column prop="configKey" label="键名" align="center" />
      <el-table-column prop="configValue" label="键值" width="200" align="center" />
      <el-table-column prop="type" label="类型" width="100" align="center">
        <template #default="scope">{{ scope.row.type === 0 ? '后台' : '前台' }}</template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            inline-prompt
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="启"
            inactive-text="禁"
            @click="updateConfig(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="small" type="text" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="small" type="text" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pageClass">
      <el-pagination
        :hide-on-single-page="true"
        v-model:currentPage="queryParams.current"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="queryParams.size"
        :pager-count="11"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <el-dialog v-model="visible" :title="title" width="500px" append-to-body destroy-on-close>
      <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
        <el-form-item label="参数名称" prop="name">
          <el-input v-model="form.name" :disabled="alowUpdate" placeholder="请输入参数名称"></el-input>
        </el-form-item>
        <el-form-item label="参数键名" prop="configKey">
          <el-input v-model="form.configKey" :disabled="alowUpdate" placeholder="请输入参数键名" />
        </el-form-item>
        <el-form-item label="参数键值" prop="configValue">
          <el-input v-model="form.configValue" placeholder="请输入参数键值" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option label="后台" value="0"></el-option>
            <el-option label="前台" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统状态" prop="status">
          <el-radio v-model="form.status" label="0">正常</el-radio>
          <el-radio v-model="form.status" label="1">停用</el-radio>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" size="large" @click="submitForm(formRef)">确认</el-button>
          <el-button @click="cancel" size="large">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="passwordVisible" width="30%" :show-close="false">
      <el-form ref="pwdFormRef" :model="pwdForm" label-width="auto" :rules="pwdRules">
        <el-form-item label="旧密码" prop="oldPwd">
          <el-input v-model="pwdForm.oldPwd" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="pwdForm.newPwd" type="password" show-password />
        </el-form-item>
        <el-form-item label="密码确认" prop="newAgainPwd">
          <el-input v-model="pwdForm.newAgainPwd" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePwd(pwdFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import type { Config } from '@/api/types/config'
import { pageList, update, add, getById, deleteByIds, changePwd } from '@/api/config'
import type { ElForm } from 'element-plus'

type FormInstance = InstanceType<typeof ElForm>
const formRef = ref<FormInstance>()
const pwdFormRef = ref<FormInstance>()

const queryParams = reactive({
  name: undefined,
  configKey: undefined,
  status: undefined,
  current: 1,
  size: 10
})

const pwdForm = reactive({
  oldPwd: undefined,
  newPwd: undefined,
  newAgainPwd: undefined,
})

const configList = ref<Config[]>([])

const multipleSelection = ref<number[] | undefined>([])

const multipleSelectionName = ref<string[]>([])

const loading = ref(false)

const visible = ref(false)

const title = ref('')

const total = ref(0)

const alowUpdate = ref(false)

const passwordVisible = ref(false)

const form = reactive<Config>({
  id: 0,
  name: '',
  configKey: '',
  configValue: '',
  type: '',
  status: '',
  createTime: '',
  remark: ''
})

const rules = reactive({
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ],
  configKey: [
    {
      required: true,
      message: '请输入健名',
      trigger: 'blur'
    }
  ],
  type: [
    {
      required: true,
      message: '请选择类型',
      trigger: 'blur'
    }
  ],
  status: [
    {
      required: true,
      message: '请选择状态',
      trigger: 'blur'
    }
  ]
})

const pwdRules = reactive({
  oldPwd: [
    {
      required: true,
      message: '请输入旧密码',
      trigger: 'blur'
    }
  ],
  newPwd: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur'
    },
    {
      message: '新密码不能和旧密码相同',
      validator: (rule: any, value: any) => value !== pwdForm.oldPwd,
      trigger: 'blur'
    }
  ],
  newAgainPwd: [
    {
      required: true,
      message: '请再次输入新密码',
      trigger: 'blur'
    },
    {
      message: '两次输入密码不相同',
      validator: (rule: any, value: any) => value === pwdForm.newPwd,
      trigger: 'blur'
    }
  ]
})

onMounted(() => {
  loadList()
})

/**
 * 加载表格数据
 */
const loadList = async () => {
  loading.value = true
  const configPage = await pageList(queryParams)
  configList.value = configPage.records
  total.value = configPage.total
  loading.value = false
}

/**
 * 更改页容量事件
 * @param val 
 */
const handleSizeChange = (val: number) => {
  queryParams.size = val
  loadList()
}

/**
 * 换页事件
 * @param val 
 */
const handleCurrentChange = (val: number) => {
  queryParams.current = val
  loadList()
}

/**
 * 多选事件
 * @param val 
 */
const handleSelectionChange = (val: Config[]) => {
  multipleSelection.value = val.map(item => item.id)
  multipleSelectionName.value = val.map(item => item.name + '/' + item.configKey)
}

/**
 * 刷新表单数据
 */
const reset = () => {
  form.id = 0
  form.name = ''
  form.configKey = ''
  form.configValue = ''
  form.type = ''
  form.status = ''
  form.remark = ''
}

/**
 * 打开新增对话框
 */
const handleAdd = () => {
  alowUpdate.value = false
  reset()
  console.log(form.id)
  title.value = '新增'
  visible.value = true
}

/**
 * 更新数据
 * @param config 
 */
const handleUpdate = async (config: Config) => {
  alowUpdate.value = true
  reset()
  title.value = '修改'
  const configById = await getById(config.id)
  form.id = configById.id
  form.name = configById.name
  form.configKey = configById.configKey
  form.configValue = configById.configValue
  form.status = configById.status
  form.type = configById.type
  form.remark = configById.remark
  visible.value = true
}

/**
 * 删除数据
 * @param config 
 */
const handleDelete = async (config: Config | any) => {
  let isDelete;
  let ids = config.id || multipleSelection.value
  let message = config.name ? config.name + '/' + config.configKey : String(multipleSelectionName.value)
  if (ids && ids.length !== 0) {
    try {
      await ElMessageBox.confirm(
        '是否要删除:' + message,
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      isDelete = await deleteByIds(ids)
      if (isDelete) {
        loadList()
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
      } else {
        ElMessage({
          message: '请选择删除数据',
          type: 'error',
        })
      }
    } catch (err) {

    }

  } else {
    ElMessage({
      message: '请选择删除数据',
      type: 'error',
    })
  }
}

/**
 * 查询数据列表
 */
const handleSearch = () => {
  loadList()
}

/**
 * 重置查询条件
 */
const handleReset = () => {
  queryParams.name = undefined
  queryParams.configKey = undefined
  queryParams.status = undefined
  queryParams.current = 1
  queryParams.size = 10
  loadList()
}

/**
 * 更新数据
 * @param config 
 */
const updateConfig = async (config: Config) => {
  const isUpdate = await update(config).finally(() => {
    loadList()
  })
  if (isUpdate) {
    ElMessage({
      message: '修改成功',
      type: 'success',
    })
  }
}

/**
 * 提交表单
 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  const valid = await formEl.validate()
  if (!valid) return false
  let ok
  let message
  if (form.id) {
    message = '修改成功'
    ok = await update(form)
  } else {
    message = '添加成功'
    ok = await add(form)
  }
  loadList()
  visible.value = false
  if (ok) {
    ElMessage({
      message,
      type: 'success',
    })
  }
}

/**
 * 关闭对话框
 */
const cancel = () => {
  reset()
  visible.value = false
}

/**
 * 修改密码对话框
 */
const handlePassword = () => {
  passwordVisible.value = true
  pwdForm.oldPwd = undefined
  pwdForm.newPwd = undefined
  pwdForm.newAgainPwd = undefined
}

const updatePwd = async (pwdFormEl: FormInstance | undefined) => {
  if (!pwdFormEl) return
  const valid = await pwdFormEl.validate()
  if (!valid) return false
  let ok = await changePwd(pwdForm);
  if (ok) {
    ElMessage({
      message: '密码修改成功',
      type: 'success',
    })
    passwordVisible.value = false
  }
  pwdForm.oldPwd = undefined
  pwdForm.newPwd = undefined
  pwdForm.newAgainPwd = undefined
}
</script>

<style lang="sass" scoped>

</style>